<template>
  <div>
    <el-card>
      <!-- 搜索框 -->
      <el-form inline >
        <el-form-item>
          <el-input v-model="roleNames.roleName" placeholder="角色名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search"  @click="search">查询</el-button>
          <el-button @click="resetSearch">清空</el-button>
        </el-form-item>
      </el-form>

      <div style="margin: 20px 0">
        <el-button type="primary"  @click="addRole" >添加</el-button>
        <el-button type="danger" @click="removeRoles" :disabled="selectedRoles.length === 0">批量删除</el-button>
      </div>

      <!-- 表格 -->
      <el-table border stripe v-loading="listLoading" @selection-change="handleSelectionChange" :data="roles" style="width: 960px">
        <el-table-column type="selection"  width="55" />
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column prop="roleName" label="角色名称" >
          <template v-slot="{row}">
            <template v-if="row.edit">
              <el-input v-model="row.roleName" class="edit-input" size="small" />
              <el-button
                class="cancel-btn"
                size="small"
                icon="el-icon-refresh"
                type="warning"
                @click="row.edit= false"
              >
                取消
              </el-button>
            </template>
            <span v-else>{{ row.roleName }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="300" align="center" >
          <template slot-scope="{row}">
            <el-button
              type="info"
              size="mini"
              title="分配权限"
              icon="el-icon-info"
              @click="$router.push(`/acl/role/auth?id=${row.id}&roleName=${row.roleName}`)"
            ></el-button>
            <el-button type="primary" size="mini" title="确定" icon="el-icon-check" @click="updateRole(row)"></el-button>
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit-outline"
              title="修改角色"
              @click="row.edit= true"
            ></el-button>
            <el-button size="small" type="danger" icon="el-icon-delete" title="删除角色" @click="removeRole(row)"/>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <el-pagination
        :current-page="page"
        :page-size="limit"
        :total="total"
        :page-sizes="[5, 10, 20, 30]"
        style="padding: 20px 0;"
        layout="prev, pager, next, jumper, ->, sizes, total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </el-card>
  </div>
</template>

<script>
import { Message } from "element-ui";
import role from "@/api/acl/role";

export default {
  data() {
    return {
      listLoading: false, //是否显示列表加载的提示
      //分页数据
      page: 1, // 当前页码
      limit: 5, // 每页数量
      total:0,
      //用户搜索的用户名
      roleNames:{
        roleName: '',
        searchRoleName: ''
      },
      //角色列表
      roles:[],
      // 所有选中的角色列表
      selectedRoles:[]
    };
  },
  mounted() {
    this.getRoles();
  },
  methods: {
    //取消修改
    cancelEdit(){

    },
    //更新角色
    async updateRole(row){
      try {
        // console.log(row);
        let result = await role.updateById({id:row.id,roleName:row.roleName})
        if(result.code == 20000){
          // console.log(result);
          Message.success('更新角色成功')
        }
        this.getRoles(this.page)
      } catch (error) {
        console.error(error);
        Message.error('更新角色失败')
      }
    },
    //当表格复选框选项发生变化的时候触发
    handleSelectionChange(selection){
      this.selectedRoles = selection.map(item => item.id)
    },
    //批量删除
    removeRoles(){
      this.$confirm('确定删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await role.removeRoles(this.selectedRoles)
        this.$message({
          type: 'success',
          message: '删除成功!',
        });
        //刷新页面
        this.getRoles()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    //删除某一个
    removeRole({id,roleName}){
      console.log(id);
      this.$confirm(`确定删除'${roleName}'吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await role.removeById(id)
        this.getRoles(this.roles.length === 1 ? this.page - 1 : this.page)
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch((error) => {
        console.error(error)
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },

    
    //添加
    addRole(){
      this.$prompt('请输入新名称', '添加角色', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(async({ value }) => {
        await role.save({roleName: value})
        this.$message({
          type: 'success',
          message: '添加角色成功'
        });
        this.getRoles()
      }).catch(() => {
        this.$message({
          type: 'warning',
          message: '取消添加'
        });       
      });
    },
    // 取消编辑
    cancelEdit(){

    },
    //-------------------------------
    //搜索
    search(){
      console.log(this.roleNames.roleName);
      this.roleNames.searchRoleName = this.roleNames.roleName
      //发送请求
      this.getRoles()
    },
    //清空
    resetSearch(){
      this.roleNames.roleName = ''
      this.roleNames.searchRoleName = ''
      this.getRoles()
    },
    //-------------------------------
    // 获取分页列表
    async getRoles() {
      this.listLoading = true;
      try {
        let result = await role.getPageList(this.page,this.limit,this.roleNames.roleName);
        
        if (result && result.code == 20000) {
          // console.log(result);
          this.roles = result.data.items.map((item)=>{
            item.edit = false ; // 用于标识是否显示编辑输入框的属性
            item.originRoleName = item.roleName  // 缓存角色名称, 用于取消
            return item
          })
          this.total = result.data.total;

          // this.roles = result.data.items;
          // this.selectedRoles = []

        }
        this.listLoading = false;
      } catch (error) {
        Message.error("获取分页数据失败");
        console.error(error);
      }
    },

    // 翻页的回调
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      // 组装数据
      this.page = val;
      //发送请求
      this.getRoles();
    },

    // 每页条数改变的回调
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      // 组装数据
      this.limit = val;
      //发送请求
      this.getRoles();
    },
  },
};
</script>

<style lang="less" scoped></style>